{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction to  Prompt Engineering II (Function calling)\n",
    "\n",
    "Below we are loading the necessary libraries, utilities, and configurations.\n",
    "\n",
    "<a href=\"https://colab.research.google.com/github/adithya-s-k/AI-Engineering.academy/blob/main/docs/PromptEngineering/function_calling.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install openai\n",
    "# !pip install python-dotenv\n",
    "# !pip install rich\n",
    "# !pip install requests"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import openai\n",
    "import requests\n",
    "from rich import print\n",
    "from dotenv import load_dotenv\n",
    "import json\n",
    "\n",
    "load_dotenv()\n",
    "\n",
    "local_api_key = os.getenv(\"GROQ_API_KEY\")\n",
    "# openai.api_key = os.getenv(\"GROQ_API_KEY\")\n",
    "\n",
    "client = openai.OpenAI(\n",
    "    base_url=\"https://api.groq.com/openai/v1\",\n",
    "    api_key=local_api_key\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_completion(messages, model=\"llama-3.2-90b-text-preview\", temperature=0, max_tokens=300, tools=None):\n",
    "    response = client.chat.completions.create(\n",
    "        model=model,\n",
    "        messages=messages,\n",
    "        temperature=temperature,\n",
    "        max_tokens=max_tokens,\n",
    "        tools=tools\n",
    "    )\n",
    "    return response.choices[0].message"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Adding two numbers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Define Function\n",
    "def add_numbers(number_1 , number_2):\n",
    "    \n",
    "    \"\"\"\n",
    "    returns the sum of two numbers\n",
    "    \"\"\"\n",
    "    \n",
    "    return int(number_1) + int(number_2)\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "add_tool = [\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"add_numbers\",\n",
    "            \"description\": \"Adds two numbers and returns the sum\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"number_1\": {\n",
    "                        \"type\": \"number\",\n",
    "                        \"description\": \"The first number to add\",\n",
    "                    },\n",
    "                    \"number_2\": {\n",
    "                        \"type\": \"number\",\n",
    "                        \"description\": \"The second number to add\",\n",
    "                    },\n",
    "                },\n",
    "                \"required\": [\"number_1\", \"number_2\"],\n",
    "            },\n",
    "        },   \n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "messages = [\n",
    "    {\n",
    "        \"role\": \"user\",\n",
    "        \"content\": \"add 66034 and 39385\"\n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Without Using Function Calling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">ChatCompletionMessage</span><span style=\"font-weight: bold\">(</span>\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">content</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'66034 + 39385 = 105419.'</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">refusal</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">role</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'assistant'</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">function_call</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">tool_calls</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>\n",
       "<span style=\"font-weight: bold\">)</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\u001b[1;35mChatCompletionMessage\u001b[0m\u001b[1m(\u001b[0m\n",
       "    \u001b[33mcontent\u001b[0m=\u001b[32m'66034 + 39385 = 105419.'\u001b[0m,\n",
       "    \u001b[33mrefusal\u001b[0m=\u001b[3;35mNone\u001b[0m,\n",
       "    \u001b[33mrole\u001b[0m=\u001b[32m'assistant'\u001b[0m,\n",
       "    \u001b[33mfunction_call\u001b[0m=\u001b[3;35mNone\u001b[0m,\n",
       "    \u001b[33mtool_calls\u001b[0m=\u001b[3;35mNone\u001b[0m\n",
       "\u001b[1m)\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "response = get_completion(messages)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Using Function Calling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">ChatCompletionMessage</span><span style=\"font-weight: bold\">(</span>\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">content</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">refusal</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">role</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'assistant'</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">function_call</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">tool_calls</span>=<span style=\"font-weight: bold\">[</span>\n",
       "        <span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">ChatCompletionMessageToolCall</span><span style=\"font-weight: bold\">(</span>\n",
       "            <span style=\"color: #808000; text-decoration-color: #808000\">id</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'call_t6e8'</span>,\n",
       "            <span style=\"color: #808000; text-decoration-color: #808000\">function</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">Function</span><span style=\"font-weight: bold\">(</span><span style=\"color: #808000; text-decoration-color: #808000\">arguments</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'{\"number_1\": 66034, \"number_2\": 39385}'</span>, <span style=\"color: #808000; text-decoration-color: #808000\">name</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'add_numbers'</span><span style=\"font-weight: bold\">)</span>,\n",
       "            <span style=\"color: #808000; text-decoration-color: #808000\">type</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'function'</span>\n",
       "        <span style=\"font-weight: bold\">)</span>\n",
       "    <span style=\"font-weight: bold\">]</span>\n",
       "<span style=\"font-weight: bold\">)</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\u001b[1;35mChatCompletionMessage\u001b[0m\u001b[1m(\u001b[0m\n",
       "    \u001b[33mcontent\u001b[0m=\u001b[3;35mNone\u001b[0m,\n",
       "    \u001b[33mrefusal\u001b[0m=\u001b[3;35mNone\u001b[0m,\n",
       "    \u001b[33mrole\u001b[0m=\u001b[32m'assistant'\u001b[0m,\n",
       "    \u001b[33mfunction_call\u001b[0m=\u001b[3;35mNone\u001b[0m,\n",
       "    \u001b[33mtool_calls\u001b[0m=\u001b[1m[\u001b[0m\n",
       "        \u001b[1;35mChatCompletionMessageToolCall\u001b[0m\u001b[1m(\u001b[0m\n",
       "            \u001b[33mid\u001b[0m=\u001b[32m'call_t6e8'\u001b[0m,\n",
       "            \u001b[33mfunction\u001b[0m=\u001b[1;35mFunction\u001b[0m\u001b[1m(\u001b[0m\u001b[33marguments\u001b[0m=\u001b[32m'\u001b[0m\u001b[32m{\u001b[0m\u001b[32m\"number_1\": 66034, \"number_2\": 39385\u001b[0m\u001b[32m}\u001b[0m\u001b[32m'\u001b[0m, \u001b[33mname\u001b[0m=\u001b[32m'add_numbers'\u001b[0m\u001b[1m)\u001b[0m,\n",
       "            \u001b[33mtype\u001b[0m=\u001b[32m'function'\u001b[0m\n",
       "        \u001b[1m)\u001b[0m\n",
       "    \u001b[1m]\u001b[0m\n",
       "\u001b[1m)\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "response = get_completion(messages, tools=add_tool)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\">{</span><span style=\"color: #008000; text-decoration-color: #008000\">'number_1'</span>: <span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">66034</span>, <span style=\"color: #008000; text-decoration-color: #008000\">'number_2'</span>: <span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">39385</span><span style=\"font-weight: bold\">}</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\u001b[1m{\u001b[0m\u001b[32m'number_1'\u001b[0m: \u001b[1;36m66034\u001b[0m, \u001b[32m'number_2'\u001b[0m: \u001b[1;36m39385\u001b[0m\u001b[1m}\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">105419</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\u001b[1;36m105419\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "args = json.loads(response.tool_calls[0].function.arguments)\n",
    "\n",
    "print(args)\n",
    "\n",
    "print(add_numbers(**args))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Counting the number of \"r\" in strawberry"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "def count_letters_in_word(word:str , letter:str):\n",
    "    \n",
    "    \"\"\"\n",
    "    returns the number of letters in word \n",
    "    \n",
    "    for example word = strawberry and letter = r\n",
    "    \n",
    "    it will return 3\n",
    "    \n",
    "    \"\"\"\n",
    "    \n",
    "    count = 0\n",
    "    for i in word:\n",
    "        if i == letter:\n",
    "            count += 1\n",
    "    return count"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "count_letters_in_word(\"strawberry\", \"r\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
    "counter_tool = [\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"count_letters_in_word\",\n",
    "            \"description\": \"counts the number of a specific letter in a given word or string\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"word\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"The word\",\n",
    "                    },\n",
    "                    \"letter\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"the letter\",\n",
    "                    },\n",
    "                },\n",
    "                \"required\": [\"word\", \"letter\"],\n",
    "            },\n",
    "        },   \n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "messages = [\n",
    "    {\n",
    "        \"role\": \"user\",\n",
    "        \"content\": \"Counting the number of 'r' in strawberry\"\n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Without function calling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">ChatCompletionMessage</span><span style=\"font-weight: bold\">(</span>\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">content</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'There are 2 \\'r\\'s in the word \"strawberry\"'</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">refusal</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">role</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'assistant'</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">function_call</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">tool_calls</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>\n",
       "<span style=\"font-weight: bold\">)</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\u001b[1;35mChatCompletionMessage\u001b[0m\u001b[1m(\u001b[0m\n",
       "    \u001b[33mcontent\u001b[0m=\u001b[32m'There are 2 \\'r\\'s in the word \"strawberry\"'\u001b[0m,\n",
       "    \u001b[33mrefusal\u001b[0m=\u001b[3;35mNone\u001b[0m,\n",
       "    \u001b[33mrole\u001b[0m=\u001b[32m'assistant'\u001b[0m,\n",
       "    \u001b[33mfunction_call\u001b[0m=\u001b[3;35mNone\u001b[0m,\n",
       "    \u001b[33mtool_calls\u001b[0m=\u001b[3;35mNone\u001b[0m\n",
       "\u001b[1m)\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "response = get_completion(messages)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### With funciton calling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">ChatCompletionMessage</span><span style=\"font-weight: bold\">(</span>\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">content</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">refusal</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">role</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'assistant'</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">function_call</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">tool_calls</span>=<span style=\"font-weight: bold\">[</span>\n",
       "        <span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">ChatCompletionMessageToolCall</span><span style=\"font-weight: bold\">(</span>\n",
       "            <span style=\"color: #808000; text-decoration-color: #808000\">id</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'call_gvn1'</span>,\n",
       "            <span style=\"color: #808000; text-decoration-color: #808000\">function</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">Function</span><span style=\"font-weight: bold\">(</span><span style=\"color: #808000; text-decoration-color: #808000\">arguments</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'{\"word\": \"strawberry\", \"letter\": \"r\"}'</span>, <span style=\"color: #808000; text-decoration-color: #808000\">name</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'count_letters_in_word'</span><span style=\"font-weight: bold\">)</span>,\n",
       "            <span style=\"color: #808000; text-decoration-color: #808000\">type</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'function'</span>\n",
       "        <span style=\"font-weight: bold\">)</span>\n",
       "    <span style=\"font-weight: bold\">]</span>\n",
       "<span style=\"font-weight: bold\">)</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\u001b[1;35mChatCompletionMessage\u001b[0m\u001b[1m(\u001b[0m\n",
       "    \u001b[33mcontent\u001b[0m=\u001b[3;35mNone\u001b[0m,\n",
       "    \u001b[33mrefusal\u001b[0m=\u001b[3;35mNone\u001b[0m,\n",
       "    \u001b[33mrole\u001b[0m=\u001b[32m'assistant'\u001b[0m,\n",
       "    \u001b[33mfunction_call\u001b[0m=\u001b[3;35mNone\u001b[0m,\n",
       "    \u001b[33mtool_calls\u001b[0m=\u001b[1m[\u001b[0m\n",
       "        \u001b[1;35mChatCompletionMessageToolCall\u001b[0m\u001b[1m(\u001b[0m\n",
       "            \u001b[33mid\u001b[0m=\u001b[32m'call_gvn1'\u001b[0m,\n",
       "            \u001b[33mfunction\u001b[0m=\u001b[1;35mFunction\u001b[0m\u001b[1m(\u001b[0m\u001b[33marguments\u001b[0m=\u001b[32m'\u001b[0m\u001b[32m{\u001b[0m\u001b[32m\"word\": \"strawberry\", \"letter\": \"r\"\u001b[0m\u001b[32m}\u001b[0m\u001b[32m'\u001b[0m, \u001b[33mname\u001b[0m=\u001b[32m'count_letters_in_word'\u001b[0m\u001b[1m)\u001b[0m,\n",
       "            \u001b[33mtype\u001b[0m=\u001b[32m'function'\u001b[0m\n",
       "        \u001b[1m)\u001b[0m\n",
       "    \u001b[1m]\u001b[0m\n",
       "\u001b[1m)\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "response = get_completion(messages, tools=counter_tool)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">3</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\u001b[1;36m3\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "args = json.loads(response.tool_calls[0].function.arguments)\n",
    "\n",
    "print(count_letters_in_word(**args))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Getting Current Weather\n",
    "\n",
    "please get you api key from [openweathermap](https://openweathermap.org/api/one-call-3#how)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_current_weather(location):\n",
    "    API_KEY = \"YOUR_API_KEY\"\n",
    "    url = f\"https://api.openweathermap.org/data/2.5/weather?q={location}&appid={API_KEY}\"\n",
    "    response = requests.get(url)\n",
    "    data = response.json()\n",
    "\n",
    "    # Extract the temperature in Kelvin\n",
    "    kelvin_temp = data['main']['temp']\n",
    "\n",
    "    # Convert Kelvin to Celsius\n",
    "    celsius_temp = kelvin_temp - 273.15\n",
    "\n",
    "    return {\"location\": location, \"temperature\": round(celsius_temp, 2)}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "get_weather_tools = [\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"get_current_weather\",\n",
    "            \"description\": \"Get the current weather in a given location\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"location\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"The city and state, e.g. San Francisco, CA\",\n",
    "                    },\n",
    "                },\n",
    "                \"required\": [\"location\"],\n",
    "            }\n",
    "        }\n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "messages = [\n",
    "    {\n",
    "        \"role\": \"user\",\n",
    "        \"content\": \"What's the weather like in Jakarta?\"\n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">ChatCompletionMessage</span><span style=\"font-weight: bold\">(</span>\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">content</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">refusal</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">role</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'assistant'</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">function_call</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">tool_calls</span>=<span style=\"font-weight: bold\">[</span>\n",
       "        <span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">ChatCompletionMessageToolCall</span><span style=\"font-weight: bold\">(</span>\n",
       "            <span style=\"color: #808000; text-decoration-color: #808000\">id</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'call_q0ny'</span>,\n",
       "            <span style=\"color: #808000; text-decoration-color: #808000\">function</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">Function</span><span style=\"font-weight: bold\">(</span><span style=\"color: #808000; text-decoration-color: #808000\">arguments</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'{\"location\": \"Jakarta\"}'</span>, <span style=\"color: #808000; text-decoration-color: #808000\">name</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'get_current_weather'</span><span style=\"font-weight: bold\">)</span>,\n",
       "            <span style=\"color: #808000; text-decoration-color: #808000\">type</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'function'</span>\n",
       "        <span style=\"font-weight: bold\">)</span>\n",
       "    <span style=\"font-weight: bold\">]</span>\n",
       "<span style=\"font-weight: bold\">)</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\u001b[1;35mChatCompletionMessage\u001b[0m\u001b[1m(\u001b[0m\n",
       "    \u001b[33mcontent\u001b[0m=\u001b[3;35mNone\u001b[0m,\n",
       "    \u001b[33mrefusal\u001b[0m=\u001b[3;35mNone\u001b[0m,\n",
       "    \u001b[33mrole\u001b[0m=\u001b[32m'assistant'\u001b[0m,\n",
       "    \u001b[33mfunction_call\u001b[0m=\u001b[3;35mNone\u001b[0m,\n",
       "    \u001b[33mtool_calls\u001b[0m=\u001b[1m[\u001b[0m\n",
       "        \u001b[1;35mChatCompletionMessageToolCall\u001b[0m\u001b[1m(\u001b[0m\n",
       "            \u001b[33mid\u001b[0m=\u001b[32m'call_q0ny'\u001b[0m,\n",
       "            \u001b[33mfunction\u001b[0m=\u001b[1;35mFunction\u001b[0m\u001b[1m(\u001b[0m\u001b[33marguments\u001b[0m=\u001b[32m'\u001b[0m\u001b[32m{\u001b[0m\u001b[32m\"location\": \"Jakarta\"\u001b[0m\u001b[32m}\u001b[0m\u001b[32m'\u001b[0m, \u001b[33mname\u001b[0m=\u001b[32m'get_current_weather'\u001b[0m\u001b[1m)\u001b[0m,\n",
       "            \u001b[33mtype\u001b[0m=\u001b[32m'function'\u001b[0m\n",
       "        \u001b[1m)\u001b[0m\n",
       "    \u001b[1m]\u001b[0m\n",
       "\u001b[1m)\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "response = get_completion(messages, tools=get_weather_tools)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\">{</span><span style=\"color: #008000; text-decoration-color: #008000\">'location'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'Jakarta'</span><span style=\"font-weight: bold\">}</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\u001b[1m{\u001b[0m\u001b[32m'location'\u001b[0m: \u001b[32m'Jakarta'\u001b[0m\u001b[1m}\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "\n",
    "args = json.loads(response.tool_calls[0].function.arguments)\n",
    "print(args)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Will only work if api key is added\n",
    "get_current_weather(**args)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Duck Duck Go Search"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install -U duckduckgo_search"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\">[</span>\n",
       "    <span style=\"font-weight: bold\">{</span>\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'title'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'Welcome to Python.org'</span>,\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'href'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'https://www.python.org/'</span>,\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'body'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'The mission of the Python Software Foundation is to promote, protect, and advance the Python </span>\n",
       "<span style=\"color: #008000; text-decoration-color: #008000\">programming language, and to support and facilitate the growth of a diverse and international community of Python </span>\n",
       "<span style=\"color: #008000; text-decoration-color: #008000\">programmers. Learn more. Become a Member Donate to the PSF. The official home of the Python Programming Language.'</span>\n",
       "    <span style=\"font-weight: bold\">}</span>,\n",
       "    <span style=\"font-weight: bold\">{</span>\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'title'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'Python For Beginners | Python.org'</span>,\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'href'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'https://www.python.org/about/gettingstarted/'</span>,\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'body'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'Learn how to get started with Python, a popular and easy-to-use programming language. Find out how</span>\n",
       "<span style=\"color: #008000; text-decoration-color: #008000\">to install, edit, and use Python, and explore its libraries, documentation, and community resources.'</span>\n",
       "    <span style=\"font-weight: bold\">}</span>,\n",
       "    <span style=\"font-weight: bold\">{</span>\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'title'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'Python Tutorial - W3Schools'</span>,\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'href'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'https://www.w3schools.com/python/'</span>,\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'body'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'W3Schools offers a comprehensive and interactive Python tutorial with examples, exercises, </span>\n",
       "<span style=\"color: #008000; text-decoration-color: #008000\">quizzes, and references. You can also download Python and get certified by completing the PYTHON course.'</span>\n",
       "    <span style=\"font-weight: bold\">}</span>,\n",
       "    <span style=\"font-weight: bold\">{</span>\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'title'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'The Python Tutorial — Python 3.13.0 documentation'</span>,\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'href'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'https://docs.python.org/3/tutorial/index.html'</span>,\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'body'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'This tutorial introduces the basic concepts and features of the Python language and system, with </span>\n",
       "<span style=\"color: #008000; text-decoration-color: #008000\">examples and exercises. It covers topics such as data structures, modules, classes, exceptions, and more.'</span>\n",
       "    <span style=\"font-weight: bold\">}</span>,\n",
       "    <span style=\"font-weight: bold\">{</span>\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'title'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'Python (programming language) - Wikipedia'</span>,\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'href'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'https://en.wikipedia.org/wiki/Python_(programming_language)'</span>,\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'body'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'Python is a high-level, general-purpose programming language.Its design philosophy emphasizes code</span>\n",
       "<span style=\"color: #008000; text-decoration-color: #008000\">readability with the use of significant indentation. [32]Python is dynamically typed and garbage-collected.It </span>\n",
       "<span style=\"color: #008000; text-decoration-color: #008000\">supports multiple programming paradigms, including structured (particularly procedural), object-oriented and </span>\n",
       "<span style=\"color: #008000; text-decoration-color: #008000\">functional programming.It is often described as a \"batteries included ...'</span>\n",
       "    <span style=\"font-weight: bold\">}</span>\n",
       "<span style=\"font-weight: bold\">]</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\u001b[1m[\u001b[0m\n",
       "    \u001b[1m{\u001b[0m\n",
       "        \u001b[32m'title'\u001b[0m: \u001b[32m'Welcome to Python.org'\u001b[0m,\n",
       "        \u001b[32m'href'\u001b[0m: \u001b[32m'https://www.python.org/'\u001b[0m,\n",
       "        \u001b[32m'body'\u001b[0m: \u001b[32m'The mission of the Python Software Foundation is to promote, protect, and advance the Python \u001b[0m\n",
       "\u001b[32mprogramming language, and to support and facilitate the growth of a diverse and international community of Python \u001b[0m\n",
       "\u001b[32mprogrammers. Learn more. Become a Member Donate to the PSF. The official home of the Python Programming Language.'\u001b[0m\n",
       "    \u001b[1m}\u001b[0m,\n",
       "    \u001b[1m{\u001b[0m\n",
       "        \u001b[32m'title'\u001b[0m: \u001b[32m'Python For Beginners | Python.org'\u001b[0m,\n",
       "        \u001b[32m'href'\u001b[0m: \u001b[32m'https://www.python.org/about/gettingstarted/'\u001b[0m,\n",
       "        \u001b[32m'body'\u001b[0m: \u001b[32m'Learn how to get started with Python, a popular and easy-to-use programming language. Find out how\u001b[0m\n",
       "\u001b[32mto install, edit, and use Python, and explore its libraries, documentation, and community resources.'\u001b[0m\n",
       "    \u001b[1m}\u001b[0m,\n",
       "    \u001b[1m{\u001b[0m\n",
       "        \u001b[32m'title'\u001b[0m: \u001b[32m'Python Tutorial - W3Schools'\u001b[0m,\n",
       "        \u001b[32m'href'\u001b[0m: \u001b[32m'https://www.w3schools.com/python/'\u001b[0m,\n",
       "        \u001b[32m'body'\u001b[0m: \u001b[32m'W3Schools offers a comprehensive and interactive Python tutorial with examples, exercises, \u001b[0m\n",
       "\u001b[32mquizzes, and references. You can also download Python and get certified by completing the PYTHON course.'\u001b[0m\n",
       "    \u001b[1m}\u001b[0m,\n",
       "    \u001b[1m{\u001b[0m\n",
       "        \u001b[32m'title'\u001b[0m: \u001b[32m'The Python Tutorial — Python 3.13.0 documentation'\u001b[0m,\n",
       "        \u001b[32m'href'\u001b[0m: \u001b[32m'https://docs.python.org/3/tutorial/index.html'\u001b[0m,\n",
       "        \u001b[32m'body'\u001b[0m: \u001b[32m'This tutorial introduces the basic concepts and features of the Python language and system, with \u001b[0m\n",
       "\u001b[32mexamples and exercises. It covers topics such as data structures, modules, classes, exceptions, and more.'\u001b[0m\n",
       "    \u001b[1m}\u001b[0m,\n",
       "    \u001b[1m{\u001b[0m\n",
       "        \u001b[32m'title'\u001b[0m: \u001b[32m'Python \u001b[0m\u001b[32m(\u001b[0m\u001b[32mprogramming language\u001b[0m\u001b[32m)\u001b[0m\u001b[32m - Wikipedia'\u001b[0m,\n",
       "        \u001b[32m'href'\u001b[0m: \u001b[32m'https://en.wikipedia.org/wiki/Python_\u001b[0m\u001b[32m(\u001b[0m\u001b[32mprogramming_language\u001b[0m\u001b[32m)\u001b[0m\u001b[32m'\u001b[0m,\n",
       "        \u001b[32m'body'\u001b[0m: \u001b[32m'Python is a high-level, general-purpose programming language.Its design philosophy emphasizes code\u001b[0m\n",
       "\u001b[32mreadability with the use of significant indentation. \u001b[0m\u001b[32m[\u001b[0m\u001b[32m32\u001b[0m\u001b[32m]\u001b[0m\u001b[32mPython is dynamically typed and garbage-collected.It \u001b[0m\n",
       "\u001b[32msupports multiple programming paradigms, including structured \u001b[0m\u001b[32m(\u001b[0m\u001b[32mparticularly procedural\u001b[0m\u001b[32m)\u001b[0m\u001b[32m, object-oriented and \u001b[0m\n",
       "\u001b[32mfunctional programming.It is often described as a \"batteries included ...'\u001b[0m\n",
       "    \u001b[1m}\u001b[0m\n",
       "\u001b[1m]\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from duckduckgo_search import DDGS\n",
    "\n",
    "results = DDGS().text(\"Python Programming\", max_results=5)\n",
    "print(results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Creating a function around duck duck go search \n",
    "\n",
    "def web_search(search_query : str, max_results):\n",
    "    try:\n",
    "        from duckduckgo_search import DDGS\n",
    "    except:\n",
    "        assert \"duckduckgo_search package not found please install using `pip install -U duckduckgo_search` \"\n",
    "\n",
    "    results = DDGS().text(search_query, max_results=int(max_results))\n",
    "    return results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [],
   "source": [
    "websearch_tool = [\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"web_search\",\n",
    "            \"description\": \"searches the web and returns top k results\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"search_query\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"The most optimal search query that will go into the search engine\",\n",
    "                    },\n",
    "                    \"max_results\": {\n",
    "                        \"type\": \"integer\",\n",
    "                        \"description\": \"the number of results based on complexity of query\",\n",
    "                    },\n",
    "                },\n",
    "                \"required\": [\"search_query\"],\n",
    "            },\n",
    "        },   \n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [],
   "source": [
    "messages = [\n",
    "    {\n",
    "        \"role\": \"user\",\n",
    "        \"content\": \"what is Nvidia current Stock Price\"\n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Without Function Calling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">ChatCompletionMessage</span><span style=\"font-weight: bold\">(</span>\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">content</span>=<span style=\"color: #008000; text-decoration-color: #008000\">\"I'm not able to provide real-time information or current stock prices. However, I can suggest some </span>\n",
       "<span style=\"color: #008000; text-decoration-color: #008000\">ways for you to find the current stock price of Nvidia.\\n\\n1. **Check online stock market platforms**: You can </span>\n",
       "<span style=\"color: #008000; text-decoration-color: #008000\">check websites like Yahoo Finance, Google Finance, or Bloomberg to get the current stock price of Nvidia </span>\n",
       "<span style=\"color: #008000; text-decoration-color: #008000\">(NVDA).\\n2. **Use a stock market app**: You can download a stock market app like Robinhood, Fidelity, or E\\\\*TRADE </span>\n",
       "<span style=\"color: #008000; text-decoration-color: #008000\">to get real-time stock prices.\\n3. **Visit Nvidia's investor relations website**: Nvidia's investor relations </span>\n",
       "<span style=\"color: #008000; text-decoration-color: #008000\">website may also provide information on the company's current stock price.\\n\\nPlease note that stock prices can </span>\n",
       "<span style=\"color: #008000; text-decoration-color: #008000\">fluctuate rapidly and may be different by the time you check.\"</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">refusal</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">role</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'assistant'</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">function_call</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>,\n",
       "    <span style=\"color: #808000; text-decoration-color: #808000\">tool_calls</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span>\n",
       "<span style=\"font-weight: bold\">)</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\u001b[1;35mChatCompletionMessage\u001b[0m\u001b[1m(\u001b[0m\n",
       "    \u001b[33mcontent\u001b[0m=\u001b[32m\"I\u001b[0m\u001b[32m'm not able to provide real-time information or current stock prices. However, I can suggest some \u001b[0m\n",
       "\u001b[32mways for you to find the current stock price of Nvidia.\\n\\n1. **Check online stock market platforms**: You can \u001b[0m\n",
       "\u001b[32mcheck websites like Yahoo Finance, Google Finance, or Bloomberg to get the current stock price of Nvidia \u001b[0m\n",
       "\u001b[32m(\u001b[0m\u001b[32mNVDA\u001b[0m\u001b[32m)\u001b[0m\u001b[32m.\\n2. **Use a stock market app**: You can download a stock market app like Robinhood, Fidelity, or E\\\\*TRADE \u001b[0m\n",
       "\u001b[32mto get real-time stock prices.\\n3. **Visit Nvidia's investor relations website**: Nvidia's investor relations \u001b[0m\n",
       "\u001b[32mwebsite may also provide information on the company's current stock price.\\n\\nPlease note that stock prices can \u001b[0m\n",
       "\u001b[32mfluctuate rapidly and may be different by the time you check.\"\u001b[0m,\n",
       "    \u001b[33mrefusal\u001b[0m=\u001b[3;35mNone\u001b[0m,\n",
       "    \u001b[33mrole\u001b[0m=\u001b[32m'assistant'\u001b[0m,\n",
       "    \u001b[33mfunction_call\u001b[0m=\u001b[3;35mNone\u001b[0m,\n",
       "    \u001b[33mtool_calls\u001b[0m=\u001b[3;35mNone\u001b[0m\n",
       "\u001b[1m)\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "response = get_completion(messages)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### With Function Calling "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\">{</span><span style=\"color: #008000; text-decoration-color: #008000\">'search_query'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'Nvidia current stock price'</span>, <span style=\"color: #008000; text-decoration-color: #008000\">'max_results'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'1'</span><span style=\"font-weight: bold\">}</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\u001b[1m{\u001b[0m\u001b[32m'search_query'\u001b[0m: \u001b[32m'Nvidia current stock price'\u001b[0m, \u001b[32m'max_results'\u001b[0m: \u001b[32m'1'\u001b[0m\u001b[1m}\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "response = get_completion(messages , tools=websearch_tool)\n",
    "args = json.loads(response.tool_calls[0].function.arguments)\n",
    "\n",
    "print(args)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\">[</span>\n",
       "    <span style=\"font-weight: bold\">{</span>\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'title'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'NVIDIA Corporation (NVDA) Stock Price, News, Quote &amp; History - Yahoo ...'</span>,\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'href'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'https://finance.yahoo.com/quote/NVDA/'</span>,\n",
       "        <span style=\"color: #008000; text-decoration-color: #008000\">'body'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'Find the latest NVIDIA Corporation (NVDA) stock quote, history, news and other vital information </span>\n",
       "<span style=\"color: #008000; text-decoration-color: #008000\">to help you with your stock trading and investing. ... Current Quarterly Annual . As of 10/14/2024 ...'</span>\n",
       "    <span style=\"font-weight: bold\">}</span>\n",
       "<span style=\"font-weight: bold\">]</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\u001b[1m[\u001b[0m\n",
       "    \u001b[1m{\u001b[0m\n",
       "        \u001b[32m'title'\u001b[0m: \u001b[32m'NVIDIA Corporation \u001b[0m\u001b[32m(\u001b[0m\u001b[32mNVDA\u001b[0m\u001b[32m)\u001b[0m\u001b[32m Stock Price, News, Quote & History - Yahoo ...'\u001b[0m,\n",
       "        \u001b[32m'href'\u001b[0m: \u001b[32m'https://finance.yahoo.com/quote/NVDA/'\u001b[0m,\n",
       "        \u001b[32m'body'\u001b[0m: \u001b[32m'Find the latest NVIDIA Corporation \u001b[0m\u001b[32m(\u001b[0m\u001b[32mNVDA\u001b[0m\u001b[32m)\u001b[0m\u001b[32m stock quote, history, news and other vital information \u001b[0m\n",
       "\u001b[32mto help you with your stock trading and investing. ... Current Quarterly Annual . As of 10/14/2024 ...'\u001b[0m\n",
       "    \u001b[1m}\u001b[0m\n",
       "\u001b[1m]\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "print(web_search(**args))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Try it Out Your Self\n",
    "\n",
    "\n",
    "- Create a simple calculator that can handle multiple opration and varied number of inputs\n",
    "- Create a Units converter that can handle multiple standard units (m , cm , km , kg , liter ...)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">Result: <span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">30</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "Result: \u001b[1;36m30\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "def calculate(operation, *numbers):\n",
    "    \"\"\"\n",
    "    Perform a calculation on a variable number of inputs.\n",
    "    \n",
    "    :param operation: String indicating the operation ('add', 'subtract', 'multiply', 'divide')\n",
    "    :param numbers: Variable number of numeric inputs\n",
    "    :return: Result of the calculation\n",
    "    \"\"\"\n",
    "    if not numbers:\n",
    "        return \"Error: No numbers provided\"\n",
    "    \n",
    "    result = numbers[0]\n",
    "    for num in numbers[1:]:\n",
    "        if operation == 'add':\n",
    "            result += num\n",
    "        elif operation == 'subtract':\n",
    "            result -= num\n",
    "        elif operation == 'multiply':\n",
    "            result *= num\n",
    "        elif operation == 'divide':\n",
    "            if num == 0:\n",
    "                return \"Error: Division by zero\"\n",
    "            result /= num\n",
    "        else:\n",
    "            return \"Error: Invalid operation\"\n",
    "    \n",
    "    return result\n",
    "\n",
    "# Function schema for the calculator\n",
    "calculator_tool = [\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"calculate\",\n",
    "            \"description\": \"Perform a calculation on multiple numbers\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"operation\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"enum\": [\"add\", \"subtract\", \"multiply\", \"divide\"],\n",
    "                        \"description\": \"The mathematical operation to perform\",\n",
    "                    },\n",
    "                    \"numbers\": {\n",
    "                        \"type\": \"array\",\n",
    "                        \"items\": {\n",
    "                            \"type\": \"number\"\n",
    "                        },\n",
    "                        \"description\": \"The numbers to perform the operation on\",\n",
    "                    },\n",
    "                },\n",
    "                \"required\": [\"operation\", \"numbers\"],\n",
    "            },\n",
    "        },\n",
    "    }\n",
    "]\n",
    "\n",
    "# Example usage\n",
    "messages = [\n",
    "    {\n",
    "        \"role\": \"user\",\n",
    "        \"content\": \"Calculate the sum of 5, 10, and 15\"\n",
    "    }\n",
    "]\n",
    "\n",
    "\n",
    "response = get_completion(messages , tools=calculator_tool)\n",
    "\n",
    "# Parse the arguments and call the function\n",
    "args = json.loads(response.tool_calls[0].function.arguments)\n",
    "result = calculate(args[\"operation\"], *args[\"numbers\"])\n",
    "print(f\"Result: {result}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\">{</span><span style=\"color: #008000; text-decoration-color: #008000\">'value'</span>: <span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">5</span>, <span style=\"color: #008000; text-decoration-color: #008000\">'from_unit'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'km'</span>, <span style=\"color: #008000; text-decoration-color: #008000\">'to_unit'</span>: <span style=\"color: #008000; text-decoration-color: #008000\">'m'</span><span style=\"font-weight: bold\">}</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\u001b[1m{\u001b[0m\u001b[32m'value'\u001b[0m: \u001b[1;36m5\u001b[0m, \u001b[32m'from_unit'\u001b[0m: \u001b[32m'km'\u001b[0m, \u001b[32m'to_unit'\u001b[0m: \u001b[32m'm'\u001b[0m\u001b[1m}\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">Result: <span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">5000.0</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "Result: \u001b[1;36m5000.0\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "def convert_units(value, from_unit, to_unit):\n",
    "    \"\"\"\n",
    "    Convert between different units of measurement.\n",
    "    \n",
    "    :param value: Numeric value to convert\n",
    "    :param from_unit: Original unit\n",
    "    :param to_unit: Target unit\n",
    "    :return: Converted value\n",
    "    \"\"\"\n",
    "    # Conversion factors (relative to base units)\n",
    "    units = {\n",
    "        \"m\": 1,\n",
    "        \"cm\": 0.01,\n",
    "        \"km\": 1000,\n",
    "        \"kg\": 1,\n",
    "        \"g\": 0.001,\n",
    "        \"l\": 1,\n",
    "        \"ml\": 0.001\n",
    "    }\n",
    "    \n",
    "    if from_unit not in units or to_unit not in units:\n",
    "        return \"Error: Invalid unit\"\n",
    "    \n",
    "    # Convert to base unit, then to target unit\n",
    "    base_value = value * units[from_unit]\n",
    "    converted_value = base_value / units[to_unit]\n",
    "    \n",
    "    return converted_value\n",
    "\n",
    "# Function schema for the units converter\n",
    "converter_tool = [\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"convert_units\",\n",
    "            \"description\": \"Convert between different units of measurement\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"value\": {\n",
    "                        \"type\": \"number\",\n",
    "                        \"description\": \"The numeric value to convert\",\n",
    "                    },\n",
    "                    \"from_unit\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"enum\": [\"m\", \"cm\", \"km\", \"kg\", \"g\", \"l\", \"ml\"],\n",
    "                        \"description\": \"The original unit of measurement\",\n",
    "                    },\n",
    "                    \"to_unit\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"enum\": [\"m\", \"cm\", \"km\", \"kg\", \"g\", \"l\", \"ml\"],\n",
    "                        \"description\": \"The target unit of measurement\",\n",
    "                    },\n",
    "                },\n",
    "                \"required\": [\"value\", \"from_unit\", \"to_unit\"],\n",
    "            },\n",
    "        },\n",
    "    }\n",
    "]\n",
    "\n",
    "# Example usage\n",
    "messages = [\n",
    "    {\n",
    "        \"role\": \"user\",\n",
    "        \"content\": \"Convert 5 kilometers to meters\"\n",
    "    }\n",
    "]\n",
    "\n",
    "response = get_completion(messages , tools=converter_tool)\n",
    "\n",
    "# Parse the arguments and call the function\n",
    "args = json.loads(response.tool_calls[0].function.arguments)\n",
    "print(args)\n",
    "result = convert_units(args[\"value\"], args[\"from_unit\"], args[\"to_unit\"])\n",
    "print(f\"Result: {result}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
